package servlet;

import dao.BlogDao;
import dao.UserDao;
import entity.Blog;
import entity.User;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhangYufei
 * Date: 2021-07-21
 * Time: 20:06
 */
@WebServlet("/blogContent")
public class BlogContentServlet extends HttpServlet {
    //判断用户是否登录
    private User checkLogin(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        if (session == null) {
            return null;
        }
        User user = (User) session.getAttribute("user");
        return user;
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");
        //0. 从req中读取当前用户信息，判定用户是否登录
        boolean isLogin = false;
        User loginUser = checkLogin(req);
        if(loginUser != null){
            isLogin = true;
        }

        //1.从请求中读取出 blogId
        String id = req.getParameter("blogId");
        if(id == null || "".equals(id)){
            resp.getWriter().write("<h3>blogId 参数错误</h3>");
            return;
        }
        int blogId = Integer.parseInt(id);
        //2.根据 blogId 在数据库中查询出博客的详细内容
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(blogId);
        if(blog == null){
            resp.sendError(404,"blogId 指定的文章不存在");
            return;
        }
        //3.根据 blog.userId 查找对应的 User 对象
        UserDao userDao = new UserDao();
        User user = userDao.selectById(blog.getUserId());
        if(user == null){
            resp.sendError(404,"该作者不存在");
            return;
        }
        //4.根据详细内容渲染到模板中
        TemplateEngine engine = (TemplateEngine) getServletContext().getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("blog",blog);
        webContext.setVariable("username",user.getUsername());
        webContext.setVariable("isLogin",isLogin);
        webContext.setVariable("loginUser",loginUser);
        String html = engine.process("artictl",webContext);
        //5.把渲染好的结果返回给客户端
        resp.getWriter().write(html);
    }
}
